/**
  ******************************************************************************
  * @file    mg_driver_rtc.c
  * @author  
  * @version V1.1
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; COPYRIGHT 2020 Shanghai Macrogiga Electronics</center></h2>
  *
  ******************************************************************************
  */
#include "mg_driver_rtc.h"
#include "mg_driver_clock.h"


void Rtc_Init(unsigned int Count /*unit 0.1s*/)
{
    if(!Count)return;
    
    CLK_SetClockGate(CLK_GATE_RTC_EN);
    
    Rtc_StopRtc();
    
    RTC->RTC_COUNT_SET = Count-1;
    RTC->RTC_UNIT_SET = 3350-1; //rtc clock 32kHz, not the exact value.
    
    Rtc_IntClear();
    RTC->RTC_INT_EN = 1;
}

void Rtc_IntClear(void)
{
//    while(RTC->RTC_INT_STATUS) //wait for clear done
//    {
//        RTC->RTC_INT_CLR = 1;
//    }
    
    RTC->RTC_INT_CLR = 1;
    
    while(RTC->RTC_INT_STATUS);
}

void Rtc_StartRtc(void)
{
    u32 delay = 0x500;
    
    RTC->RTC_ENABLE = 1;
    
    while(RTC->RTC_ENABLE != 1);
    
    while(delay--);
}

void Rtc_StopRtc(void)
{
    RTC->RTC_ENABLE = 0;
    
    while(RTC->RTC_ENABLE != 0);
}
